<?php
namespace app\store\controller;

use app\common\controller\StoreBase;
use app\common\model\Dict as DictModel;
use app\store\model\DictData;
use app\store\model\StoreGroup;
use app\store\model\StoreRule;

class Dict extends StoreBase
{
    protected $noAuth = ['get_dictionary'];

    /**
     * 字典列表
     * @return mixed
     */
    public function index()
    {
        return $this->fetch('index');
    }
    public function index_json($dict_id='')
    {
        $model = new DictData();
        if(!empty($dict_id)){
            $model = $model->where('dict_id',$dict_id);
        }
        $list = $model->order('sort_order asc')->select();
        $authRule = collection($list)->toArray();
        $data = [];
        foreach ($authRule as $k => $v) {
            $data[$k] = array(
                'id' =>$v['id'],
                "name" => $v['name'],
                "remark" => $v['remark'],
                "image" => $v['image'],
                "parentId" =>$v['pid'],
                "sort_order" =>$v['sort_order'],
                "status" =>$v['status'],
                "createTime" =>'',
                "updateTime" =>'',
                "open"=> $v['status']?true:false
            );
        }
        $arrayName = array('code' =>0,'msg' =>'加载成功','count' =>count($list),'data' =>$data);
        return json_encode($arrayName);
    }

    /**
     * 获取字典分类
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get_dictionary()
    {
        $dict = new DictModel();
        //判断权限-获取我的权限
        $auth_id = my_rule();
        $dict = $dict->where('auth_id','in',$auth_id);
        $list = $dict->order('auth_id asc,id desc')->select();
        $data = [];
        foreach ($list as $k=>$r){
            $data[$k]['leftid'] = $k;
            $data[$k]['dictId'] = $r['id'];
            $data[$k]['dictName'] = $r['name'];
        }
        return json(['code'=>'0','msg'=>'','count'=>count($list),'data'=>$data]);
    }

    /**
     * 添加
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add($dict_id)
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $param['store_id'] = StoreId();
            $verify = input('_verify', true);
            //验证规则
            if($verify!='0'){
                try{
                    $this->validate($param, 'dictData');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
            //检查是否存在值
            $data = DictData::where('dict_id',$param['dict_id'])->find();
            if(!$data){
                $param['is_default'] = 1;
            }
            $result = DictData::create($param);
            if ($result == true) {
                clear_store_cache();//清空整个商户的缓存
                insert_user_log('添加了字典');
                $this->success('添加成功');
            } else {
                $this->error($this->errorMsg);
            }
        }
        //查询是否多级
        $dict = DictModel::find($dict_id);
        $category = DictData::where('dict_id',$dict_id)->where(['status' => 1])->order('sort_order asc')->select();
        return $this->fetch('save',[
            'dict'     => $dict,
            'category' => list_to_level($category)
        ]);
    }

    /**
     * 编辑
     * @param $id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit($id)
    {
        if ($this->request->isPost()) {
            $param  = $this->request->param();
            $verify = input('_verify', true);
            //验证规则
            if($verify!='0'){
                try{
                    $this->validate($param, 'dictData');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
            //更新数据
            $resule = DictData::update($param,['id'=>$param['id']]);
            if ( $resule == true) {
                $data = DictData::where('id',$id)->find();
                clear_store_cache();//清空整个商户的缓存
                insert_user_log('修改了字典名称');
                $this->success('修改成功');
            } else {
                $this->error($this->errorMsg);
            }
        }
        $data = DictData::where('id',$id)->find();
        //查询是否多级
        $dict = DictModel::find($data['dict_id']);
        $category = DictData::where('dict_id',$data['dict_id'])->where(['status' => 1])->order('sort_order asc')->select();
        return $this->fetch('save', [
            'data'     => $data,
            'dict'     => $dict,
            'category' => list_to_level($category)
        ]);
    }

    /**
     * 删除
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function del()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            DictData::destroy($param['id']);
            $data = DictData::where('id',$param['id'])->find();
            clear_store_cache();//清空整个商户的缓存
            insert_user_log('删除了字典名称');
            $this->success('删除成功');
            
        }
    }

    /**
     * 设置默认
     * @param $id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit_default($id)
    {
        if ($this->request->isPost()) {
            //查询当前值
            $data = DictData::where('id',$id)->find();
            //将所有默认都去除
            DictData::where('dict_id',$data['dict_id'])->update(['is_default'=>0]);
            //设置当前ID值为默认
            DictData::where('id',$id)->update(['is_default'=>1]);
            insert_user_log('修改了默认值');
            clear_store_cache();//清空整个商户的缓存
            $this->success('修改成功');
        }
    }

}
